import smtplib, sys

import email
from email.mime.text import MIMEText
import email.MIMEMultipart
import email.MIMEBase
import time
import os, getopt

mail_host = ""
mail_user = ""
mail_pass = ""
attach_file = None
mail_text = ""
mail_from = ""
mail_to_list = []
mail_subject = ""


def send_mail(to_list, sub, text="", attachment=None):
    global mail_from

    msg = email.MIMEMultipart.MIMEMultipart()

    text_msg = MIMEText(text ,_subtype='plain',_charset='utf-8')
    msg.attach(text_msg)

    contype = 'application/octet-stream'
    maintype, subtype = contype.split('/', 1)

    if attachment != None:
        data = open(attachment, 'rb')
        file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
        file_msg.set_payload(data.read())
        data.close()
        email.Encoders.encode_base64(file_msg)
        file_msg.add_header('Content-Disposition', 'attachment',
                filename = os.path.basename(attachment))

        msg.attach(file_msg)

    if mail_from == "":
        mail_from = mail_user

    msg['Subject'] = sub
    msg['From'] = mail_from
    msg['To'] = ";".join(to_list)
    msg['Date'] = email.Utils.formatdate()
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user,mail_pass)
        server.sendmail(mail_from, to_list, msg.as_string())
        server.close()
        return True
    except Exception, e:
        print(str(e))
        return False

def usage():
    print("Usage: %s <options>" % sys.argv[0])
    print("-h      --- this help message");
    print("-m      --- smtp server")
    print("-u      --- smtp user")
    print("-p      --- smtp password")
    print("-f      --- attachment file")
    print("-t      --- mail destination address")
    print("-s      --- mail subject")
    print("-T      --- mail text")
    print("-F      --- mail from string")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        usage()
        sys.exit(1)

    opts, args = getopt.getopt(sys.argv[1:], "hm:u:p:f:t:s:T:F:", [])

    for o, a in opts:
        if o == "-h":
            useage()
            sys.exit(0)
        elif o == "-f":
            attach_file = a
        elif o == "-m":
            mail_host = a
        elif o == "-u":
            mail_user = a
        elif o == "-p":
            mail_pass = a
        elif o == "-t":
            mail_to_list.append(a)
        elif o == "-s":
            mail_subject = a
        elif o == "-T":
            mail_text = a
        elif o == "-F":
            mail_from = a
        else:
            print("Unkonwn option, ignoring")

    if mail_to_list == []:
        print("the mail destination can not be empty!")
        exit(1)
    elif mail_host == "":
        print("the mail server must be specified !")
        exit(1)
    elif mail_user == "":
        print("the mail server user must be specified !")
        exit(1)
    elif mail_pass == "":
        print("the mail server password must be specified !")
        exit(1)

    result = send_mail(mail_to_list, mail_subject, text = mail_text, attachment = attach_file)

    if result == False:
        print("send email to %s failed!" % ';'.join(mail_to_list))
    else:
        print("send email to %s success!" % ';'.join(mail_to_list))
    
